package com.apps.ftapp.activity;

import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.apps.ftapp.R;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.CountDownTimerUtils;
import com.apps.ftapp.util.DensityUtils;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.MobileUtil;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

/**
 * 忘记密码
 */
public class ForgetPwdActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.mobile)
    EditText mobile;
    @BindView(R.id.yanzhengma)
    EditText yanzhengma;
    @BindView(R.id.send)
    TextView send;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.backBtn)
    ImageView back_btn;


    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);
        ButterKnife.bind(this);


        next.setOnClickListener(this);
        send.setOnClickListener(this);


        back_btn.setOnClickListener(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(ForgetPwdActivity.this, 0, null);
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        getAndroiodScreenProperty();
        ViewGroup.LayoutParams params = next.getLayoutParams();
        params.height = (int) (((DensityUtils.dp2px(this, (Constant.SCREEN_WIDTH - 120)) / 231.00)) * 38);
        next.setLayoutParams(params);
    }

    @Override
    public void onClick(View view) {
        String mob = mobile.getText().toString();
        String code = yanzhengma.getText().toString();
        switch (view.getId()) {
            case R.id.next:

                if (!MobileUtil.isMobileNO(mob)) {
                    Toasty.normal(getApplicationContext(), "请输入正确的手机号").show();
                    return;
                }
                if ("".equals(code)) {
                    Toasty.normal(getApplicationContext(), "请输入验证码").show();
                    return;
                }

                regist(mob, code);
                break;

            case R.id.send:
                //判断手机号是否正确

                if (!MobileUtil.isMobileNO(mob)) {
                    Toasty.normal(getApplicationContext(), "请输入正确的手机号").show();
                    return;
                }
                CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(send, 60000, 1000); //倒计时1分钟
                mCountDownTimerUtils.start();
                //调用发短信接口
                sendCode(mob);
                break;

            case R.id.backBtn:
                finish();
                break;
        }

    }


    public boolean sendCode(String mobile) {
        RequestParams params = new RequestParams();
        params.add("mobile", mobile);
        params.add("sendcode", "ftBdA80znQ0jyRig");
        Async.post("sms/message", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    // L.i("main",new String(responseBody));
                    //请求成功

                    Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                    if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                        Toasty.normal(getApplicationContext(), "验证码发送成功").show();
                    } else {
                        Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                    }
                    L.i("main", jsonBean.toString());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

        return true;
    }


    public void regist(final String mobile, String code) {
        RequestParams params = new RequestParams();
        params.add("mobile", mobile);
        params.add("mobile_code", code);
        Async.post("password/reset/by_sms", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    //请求成功
                    Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                    L.i("main", jsonBean.toString());
                    if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                        Toasty.normal(getApplicationContext(), "验证成功，请设置密码").show();
                        HashMap<String, Object> map = new HashMap();
                        map.put("token", Tools.isNull(jsonBean.get("token")));
                        ActivitySkipUtil.skipAnotherActivity(ForgetPwdActivity.this, ResetPwdActivity.class, map);
                        finish();
                    } else {
                        Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    public void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;// 屏幕宽度（像素）
        int height = dm.heightPixels; // 屏幕高度（像素）
        float density = dm.density;//屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;//屏幕密度dpi（120 / 160 / 240）
        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);//屏幕宽度(dp)
        Constant.SCREEN_WIDTH = screenWidth;
        //int screenHeight = (int) (height / density);//屏幕高度(dp)
    }

}
